package org.snail.proxy.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snail.proxy.proto.Packet;

/**
 * @author fxd
 * @version 1.0.0
 * @ClassName ProtoEncoder.java
 * @Description TODO
 * @createTime 2021年09月27日 14:06:00
 */
public class ProtoEncoder extends MessageToByteEncoder<Packet> {
    private static final Logger log = LoggerFactory.getLogger(ProtoEncoder.class);
    private final int limit;

    public ProtoEncoder(int limit){
        this.limit = limit;
    }

    protected void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf out) throws Exception{
        try{
            byte[] bytes = packet.getBytes();// 将对象转换为byte
            int length = bytes.length;// 读取 ProtoMsg 消息的长度
            ByteBuf buf = Unpooled.buffer(17 + length);

            buf.writeByte(packet.getHead());
            buf.writeInt(packet.getCmd());
            buf.writeLong(packet.getSid());
            buf.writeInt(packet.getBytes().length);
            buf.writeBytes(packet.getBytes());
            out.writeBytes(buf);
//            final Channel channel = ctx.channel();
//    		Integer integer = channel.attr(DAttributeKey.FLUSH).get();
//    		if (integer == null) {
//    			integer = 0;
//    		}
//    		channel.attr(DAttributeKey.FLUSH).set(integer + 1);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
